package net.xdclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.OSSConfig;
import net.xdclass.service.FileService;
import net.xdclass.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String upload(MultipartFile file) {
        String bucketname = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //oss构建客户端
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        //获取当前日期  并进行格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        //文件上传路径
        String folder = dateTimeFormatter.format(now);
        String fileName = CommonUtil.generateUUID();
        String extendsion = originalFilename.substring(originalFilename.lastIndexOf("."));

        //创建文件夹
        String newFileName = "user/" + folder + "/" + fileName + extendsion;

        try {
            PutObjectResult putObjectResult = oss.putObject(bucketname, newFileName, file.getInputStream());
            if (putObjectResult != null) {
                //返给前端
                String imgUrl = "https://" + bucketname + "." + endpoint + "/" + newFileName;
                return imgUrl;
            }
        } catch (IOException e) {
            log.info("上传文件失败");
        } finally {
            oss.shutdown();
        }

        return null;
    }
}
